package com.kotlin.demo.ui

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.unit.TextUnit
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.kotlin.demo.constant.Constants
import com.kotlin.demo.helper.DialogHelper
import com.kotlin.demo.tools.UiUtils
import com.kotlin.demo.ui.state.SideEffectState
import com.kotlin.demo.ui.state.TranslateIntent
import com.kotlin.demo.ui.state.TranslateState
import com.kotlin.demo.ui.viewmodel.TranslateViewModel
import org.koin.mp.KoinPlatform.getKoin

@Composable
internal fun homePage() {
    //初始化依赖注入
    val viewModel: TranslateViewModel = getKoin().get<TranslateViewModel>()
    // 监听 StateFlow 并转换为 Compose 的 State 通过 collectAsState() 方法就可以实现
    val translateData by viewModel.state.collectAsState()//翻译结果
    val sideEffectState = translateData.sideEffectState
    // LaunchedEffect 协成使用方法 加载可以处理 数据未使用前 的报错
    LaunchedEffect(Unit) {//Unit 表示 只执行一次 也可以传入其他key
        viewModel.processIntent(TranslateIntent.TranslateResList(isShowTips = false, isShowResList = false))
    }
    // UI 界面对于副作用的处理
    when (sideEffectState) {
        is SideEffectState.ShowToast -> {//弹出提示框
            DialogHelper.showTipsDialog(sideEffectState.message) {
                sideEffectState.message = ""
            }
        }
    }

    Column(modifier = Modifier.padding(16.dp).background(Color.White).fillMaxSize()) {
        //翻译路径
        resView(translateData, viewModel)
        //翻译输入
        translateInputView()
        //菜单栏
        menuButtonView(viewModel)
        //结果输出
        outTranslateView()
    }
}

/**
 * 翻译输入界面
 */
@Composable
internal fun translateInputView() {
    Spacer(Modifier.padding(top = 8.dp))
    OutlinedTextField(
        label = { Text("请输入翻译内容", style = TextStyle(fontSize = 14.sp)) },
        value = Constants.translateInput.value,
        singleLine = true,
        onValueChange = { Constants.translateInput.value = it },
        placeholder = { Text("请输入翻译内容", style = TextStyle(fontSize = 14.sp)) },
        textStyle = TextStyle(
            fontSize = 14.sp, lineHeight = TextUnit.Unspecified, color = Color.Black
        ),
        modifier = Modifier.fillMaxWidth().padding(0.dp) // 使 TextField 填满其父组件的宽度
    )
}

/**
 * 翻译结果输出界面
 */
@Composable
internal fun outTranslateView() {
    var textFieldValue by remember { mutableStateOf(TextFieldValue(UiUtils.formatAndColorizeJson(Constants.translateResultText.value))) }
    // 监听 json 的变化，更新 TextFieldValue
    LaunchedEffect(Constants.translateResultText.value) {
//        此方法会让用户角标不能保持一致
//        textFieldValue = TextFieldValue(StringsUtils.formatAndColorizeJson(Constants.translateResultText.value))
        // 此方法能保证 游标位置保留 只更新数据内容
        textFieldValue =
            textFieldValue.copy(annotatedString = UiUtils.formatAndColorizeJson(Constants.translateResultText.value))
    }
    Spacer(Modifier.padding(top = 8.dp))
    Text("翻译结果如下：", style = TextStyle(fontSize = 14.sp))
    Spacer(Modifier.padding(top = 16.dp))
    //翻译结果
    OutlinedTextField(
        value = textFieldValue,
        onValueChange = { newTextFieldValue ->
            Constants.translateResultText.value = newTextFieldValue.text
            textFieldValue = newTextFieldValue
        },
        placeholder = { Text("翻译结果空空如也~~~", style = TextStyle(fontSize = 14.sp)) },
        textStyle = TextStyle(
            fontSize = 14.sp, lineHeight = TextUnit.Unspecified, color = Color.Black, fontFamily = FontFamily.Monospace
        ),
        modifier = Modifier.height(300.dp).fillMaxWidth().padding(0.dp) // 使 TextField 填满其父组件的宽度
    )
}

/**
 * 菜单栏布局
 */
@Composable
internal fun menuButtonView(viewModel: TranslateViewModel) {
    Spacer(Modifier.padding(top = 8.dp))
    Row {
        getComButton("开始翻译") {
            // 去翻译
            viewModel.processIntent(TranslateIntent.TranslateMultilingual)
        }
        getComButton("写入翻译") {
            if (Constants.resPath.value.isEmpty()) {
                DialogHelper.showTipsDialog("写入路径不能为空!")
                return@getComButton
            }
            if (Constants.translateResultText.value.isEmpty()) {
                DialogHelper.showTipsDialog("翻译内容不能为空!")
                return@getComButton
            }
            DialogHelper.showEditKeyDialog()
        }
        getComButton("替换翻译") {
            if (Constants.resPath.value.isEmpty()) {
                DialogHelper.showTipsDialog("写入路径不能为空!")
                return@getComButton
            }
            DialogHelper.showReplaceKeyDialog()
        }
        getComButton("移除翻译") {
            if (Constants.resPath.value.isEmpty()) {
                DialogHelper.showTipsDialog("要移除的路径不能为空!")
                return@getComButton
            }
            DialogHelper.showRemoveKeyDialog()
        }
        getComButton("预览翻译") {
            if (Constants.resPath.value.isEmpty()) {
                DialogHelper.showTipsDialog("要预览的多语言路径不能为空!")
                return@getComButton
            }
            DialogHelper.showFindKeyDialog()
        }
        getComButton("导出翻译") {
            if (Constants.resPath.value.isEmpty()) {
                DialogHelper.showTipsDialog("要导出的多语言路径不能为空!")
                return@getComButton
            }
            DialogHelper.showExportDialog()
        }
    }
}

@Composable
internal fun getComButton(text: String, click: () -> Unit) {
    OutlinedButton(onClick = {
        click()
    }, content = { Text(text, style = TextStyle(fontSize = 14.sp)) }, modifier = Modifier.padding(end = 8.dp))
}

/**
 * 翻译路劲 布局
 */
@Composable
internal fun resView(resList: TranslateState, viewModel: TranslateViewModel) {
    Row(verticalAlignment = Alignment.CenterVertically) {
        OutlinedTextField(
            value = Constants.resPath.value,
            label = { Text("输出多语言文件路径", style = TextStyle(fontSize = 14.sp)) },
            singleLine = true,
            onValueChange = {
                Constants.resPath.value = it.replace("\n", "")
                    .replace("\r", "").trim()
            },
            textStyle = TextStyle(
                fontSize = 14.sp, lineHeight = TextUnit.Unspecified, color = Color.Black
            ), // 设
            modifier = Modifier.weight(weight = 1.0f, fill = false).fillMaxWidth()
                .padding(0.dp) // 使 TextField 填满其父组件的宽度
        )
        IconButton(onClick = {
            viewModel.processIntent(TranslateIntent.TranslateResList(isShowTips = true, isShowResList = true))
        }) {
            Icon(Icons.Filled.MoreVert, contentDescription = "选择路径")
        }
        IconButton(onClick = {
            DialogHelper.showAddResDialog()
        }) {
            Icon(Icons.Default.Add, contentDescription = "添加路径")
        }
        IconButton(onClick = {
            //删除res路径
            viewModel.processIntent(TranslateIntent.TranslateDelResList)
        }) {
            Icon(Icons.Default.Delete, contentDescription = "删除路径")
        }
        // 鼠标点击的地方弹出的 菜单
        CursorDropdownMenu(
            expanded = Constants.isExpandResPath.value, // 可以设置为 false 以默认关闭下拉菜单
            onDismissRequest = { /* 处理下拉菜单关闭的逻辑 */
                Constants.isExpandResPath.value = false
            }) {
            resList.translateResList.forEach { option ->
                DropdownMenuItem(
                    content = { Text(option.resTag) },
                    // 选择选项时更新状态变量
                    onClick = {
                        Constants.resPath.value = option.resPath.replace("\n", "").replace("\r", "").trim()
                        Constants.isExpandResPath.value = !Constants.isExpandResPath.value
                    },
                )
            }
        }
    }
}


